package controllers;

import java.util.List;

import models.Post;
import play.Logger;
import play.mvc.Controller;

public class Admin extends Controller {

	public static void index() {
		List<Post> posts = Post.all().fetch();
		render(posts);
	}

	public static void form(Long id) {
		System.out.println("id : "+id);
		if (id != null) {
			Post post = Post.findById(id);
			render(post);
		}
		render();
	}

	public static void delete(long id) {
		Post post = Post.findById(id);
		post.delete();
		flash.success("L'article " + id + " a bien été supprimé");
		index();
	}

	public static void save(Long id, String title, String content) {
		Logger.info("Save id = %s, title = %s, content = %s", id, title, content);
		if (id == null) {
			Post post = new Post(title, content);
			post.insert();
			flash.success("L'article " + post.id + " a bien été inséré");
		} else {
			Post post = Post.findById(id);
			post.content = content;
			post.title = title;
			post.update();
			flash.success("L'article " + post.id + " a bien été mis à jour");
		}

		index();
	}

}
